import express from "express";
import { createBundleRenderer } from "vue-server-renderer";
import { createServer } from "http";
import fs from "fs";
import api from "./api";

// Render bundle
let bundle = JSON.parse(
  fs.readFileSync("./vue-ssr-server-bundle.json").toString()
);
// Rendering function
const renderer = createBundleRenderer(bundle, {
  runInNewContext: false,
  template: fs.readFileSync("index.html").toString()
});

// master server
let httpServer = express();

// Create static directory
httpServer.use("/assets", express.static("./assets"));

// Create API route
httpServer.use("/api", api);

// Vue routing
httpServer.get("*", async (req, res) => {
  const context = { url: req.url };
  renderer.renderToString(context, (err: any, html: string) => {
    if (err) {
      res.writeHead(err.code);
      res.end("Error " + err.code);
    }
    res.end(html);
  });
});

// Set the port to 8080
let server = createServer(httpServer);
console.log('服务器已开启，地址: http://localhost:8080');
server.listen(8080);